package com.viknix.threadpool.manager.client.template;

import com.viknix.threadpool.manager.client.builder.ThreadPoolBuilder;
import com.viknix.threadpool.manager.client.factory.BlockingQueueFactory;
import com.viknix.threadpool.manager.client.factory.RejectedHandlerFactory;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Dongqi
 * @Date: 2021-10-21 21:52
 * @Version 1.0
 * @Description: 普通线程池模板工具
 */
public class ThreadPoolExecutorTemplate extends AbstractThreadPoolExecutorTemplate {

    private static volatile ThreadPoolExecutorTemplate instance;

    private ThreadPoolExecutorTemplate() {
    }

    public static synchronized ThreadPoolExecutorTemplate getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolExecutorTemplate.class) {
                if (instance == null) {
                    instance = new ThreadPoolExecutorTemplate();
                }
            }
        }
        return instance;
    }

    @Override
    protected ThreadPoolExecutor buildThreadPoolExecutor(ThreadPoolBuilder builder) {
        return new ThreadPoolExecutor(
                builder.getCorePoolSize(),
                builder.getMaxPoolSize(),
                builder.getKeepAliveTime(),
                builder.getTimeUnit(),
                BlockingQueueFactory.createBlockingQueue(builder.getBlockingQueueCode(), builder.getCapacity()),
                builder.getThreadFactory(),
                RejectedHandlerFactory.createPolicy(builder.getRejectedHandlerCode()));
    }
}
